<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
     let getStrBytes = function (str) {
      if (str == null || str === undefined) return 0;
      if (typeof str != "string") {
        return 0;
      }
      var total = 0, charCode, i, len;
      for (i = 0, len = str.length; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode <= 0x007f) {
          total += 1;//字符代码在000000 – 00007F之间的，用一个字节编码
        } else if (charCode <= 0x07ff) {
          total += 2;//000080 – 0007FF之间的字符用两个字节
        } else if (charCode <= 0xffff) {
          total += 3;//000800 – 00D7FF 和 00E000 – 00FFFF之间的用三个字节，注: Unicode在范围 D800-DFFF 中不存在任何字符
        } else {
          total += 4;//010000 – 10FFFF之间的用4个字节
        }
      }
      return total;
    };
    console.log(getStrBytes("js 获取字符串所占字节数 (UTF-8编码)"))

  </script>
</body>

</html>